import { request } from "../../utils/request"
import Toast from '@vant/weapp/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo:{},
    songList:[],
    searchList:[],
    showShare: false,
    showInfo:false,
    options: [
      { name: '微信', icon: 'wechat', openType: 'share' },
      { name: '微博', icon: 'weibo' },
      { name: '复制链接', icon: 'link' },
      { name: '分享海报', icon: 'poster' },
      { name: '二维码', icon: 'qrcode' },
    ],
  },
  login(){
    return new Promise((resolve,reject)=>{
      wx.login({
        success(res){
          resolve(res)
        },
        fail(err){
          reject(err)
        }
     })
    })
  },
  async getUserInfo(){
    //
    const getInfo = ()=> wx.getUserProfile({desc:"注册登录"})
    const [info,loginData] =  await Promise.all([getInfo(),this.login()])
    const code = (loginData as {code:string}).code
    const userInfo = info.userInfo
    let UserData = {code,...userInfo}
    let user =  await request("/user","POST",{...UserData}) as any
    if(user.statusCode==200){
      let token = user.data[0].openId
      let userInfo = user.data[0]
      wx.setStorageSync('token',token)
      wx.setStorageSync('userInfo',userInfo)
      wx.setStorageSync('isLogin',true)
      this.setData({
        userInfo
      })
    }
  },
  logout(){
    wx.removeStorageSync("token")
    wx.removeStorageSync("userInfo")
    wx.removeStorageSync("isLogin")
    this.setData({
        userInfo:"" as any
    })
  },
  toSearch(){
    let searchList = this.data.searchList
    wx.navigateTo({
      url:"/pages/userSearch/userSearch",
      success(res){
        res.eventChannel.emit('context',searchList)
      }
    })
  },
  toSong(){
    let songList = this.data.songList
    wx.navigateTo({
      url:"/pages/userSong/userSong",
      success(res){
        res.eventChannel.emit('context',songList)
      }
    })
  },
  toPosition(){
    wx.navigateTo({
      url:"/pages/position/position"
    })
  },
  toDaiLiu(){
    wx.navigateTo({
      url:"/pages/dailiu/dailiu"
    })
  },
  // 修改用户信息
  alterUser(){
    wx.navigateTo({
      url:"/pages/alterUser/alterUser"
    })
  },
  share(){
    this.setData({
      showShare:true
    })
  },
  onClick() {
    this.setData({ showShare: true });
  },
  onClose() {
    this.setData({ showShare: false });
  },
  infoClose(){
    this.setData({
      showInfo:false
    })
  },
  showInfo(){
    this.setData({
      showInfo:true
    })
  },
  onSelect(event:any) {
    Toast(event.detail.name);
    this.onClose();
  },
  async init(){
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo
    })
    let id = userInfo.id
    let songData = await request(`/song/user/${id}`) as {data:any}
    let searchData = await request(`/serch/user/${id}`) as {data:any}
    this.setData({
      songList:songData.data,
      searchList:searchData.data
    })
  },
  onShow(){
    this.init()
  }
})